package com.springboot.test.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json和对象处理类
 */
public class JsonUtils {
    public static String objectToJson(Object o) {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = null;
        try {
            json = objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return json;
    }
    //泛型指定输入输出类型
    public static <T> T jsonToObject(String json, Class<T> valueType) {
        ObjectMapper objectMapper = new ObjectMapper();
        T value = null;
        try {
            value = objectMapper.readValue(json, valueType);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return value;
    }
}
